package org.linkerproject.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class MyHttpHandler implements HttpHandler {

	private String localPath;

	public MyHttpHandler(String localPath) {
		this.localPath = localPath;
	}

	public void save(String url, String html) {
		int index = url.lastIndexOf("/");
		String fileName = url.substring(index);
		// System.out.println("saving:" + fileName);

		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(localPath
					+ fileName));
			bw.write(html);
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void handle(HttpExchange httpExchange) throws IOException {
		// System.out.println("handle:" + httpExchange.getRequestURI());
		String response = null;

		response = getLocalFile(httpExchange.getRequestURI().toString());

		// System.out.println(response);
		if (response == null) {
			response = "Hello world!";
		}

		httpExchange.sendResponseHeaders(200, response.length());
		OutputStream out = httpExchange.getResponseBody();
		out.write(response.getBytes());
		out.close();
	}

	private String getLocalFile(String fileUrl) {
		File file = new File(localPath + fileUrl);
		// System.out.println(file.getAbsolutePath());

		if (!file.exists()) {
			return null;
		}

		try {
			StringBuffer content = new StringBuffer("");
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;
			while ((line = br.readLine()) != null) {
				content.append(line);
			}

			return content.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
}
